package com.xdtech.hotel.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.xdtech.common.utils.ApplicationContextUtil;
import com.xdtech.common.utils.ExcelHelper;
import com.xdtech.common.utils.JsonUtil;
import com.xdtech.core.init.InitCacheData;
import com.xdtech.hotel.model.Room;
import com.xdtech.hotel.model.RoomConfig;
import com.xdtech.hotel.monitor.ClientMonitor;
import com.xdtech.hotel.monitor.RoomMonitorInfo;
import com.xdtech.hotel.protocol.manager.RoomMonitor;
import com.xdtech.hotel.service.RoomService;
import com.xdtech.hotel.util.ComponentHandler;
import com.xdtech.hotel.vo.DeviceLinkItem;
import com.xdtech.hotel.vo.RoomItem;
import com.xdtech.sys.aspect.SystemControllerLog;
import com.xdtech.sys.vo.CodeValueItem;
import com.xdtech.sys.vo.RoleItem;
import com.xdtech.web.model.Pagination;
import com.xdtech.web.model.ResultMessage;

/**
 * 
 * @author max.zheng
 * @create 2015-04-01 22:53:23
 * @since 1.0
 * @see
 */
@Controller
@Scope("prototype")
public class RoomController {
	private static Log log = LogFactory.getLog(RoomController.class);
	@Autowired
	private RoomService roomService;
	@RequestMapping(value="/room.do",params = "room")
	public ModelAndView skipRoom() {
		return new ModelAndView("hotel/room/room_ftl");
	}
	
	@RequestMapping(value="/room.do",params="loadList")
	@ResponseBody
	public Map<String, Object> loadList(RoomItem item,Pagination pg) {
		Map<String, Object> results =  roomService.loadPageDataByConditions(pg,item,"findRoomByCondition");
		return results;
	}
	
	@RequestMapping(value="/room.do",params = "editRoom")
	public ModelAndView editRoom(HttpServletRequest request,Long roomId) {
		if (roomId!=null) {
			request.setAttribute("roomItem", roomService.loadRoomItem(roomId));
		}
		return new ModelAndView("hotel/room/editRoom_ftl");
	}
	
	@RequestMapping(value="/room.do",params = "saveRoom")
	@ResponseBody
	public ResultMessage saveRoom(RoomItem item) {
		ResultMessage r = new ResultMessage();
		if (roomService.saveOrUpdateRoom(item)) {
			r.setSuccess(true);
		}else {
			r.setSuccess(false);
		}
		return r;
	}
	
	@RequestMapping(value="/room.do",params = "deleteRoomItems")
	@ResponseBody
	@SystemControllerLog(description = "删除客房")
	public ResultMessage deleteRoomItems(String ids) {
		ResultMessage r = new ResultMessage();
		if (StringUtils.isNotEmpty(ids)) {
			String[] tempIds = ids.split(",");
			List<Long> roomIds = new ArrayList<Long>();
			for (String id : tempIds) {
				roomIds.add(Long.valueOf(id));
			}
			roomService.deleteRoomInfo(roomIds);
			r.setSuccess(true);
		}else {
			r.setSuccess(false);
		}
		return r;
	}
	
	@RequestMapping(value="/room.do",params = "loadAllMonitingRooms")
	@ResponseBody
	public Collection<RoomMonitorInfo> loadAllMonitingRooms(HttpServletRequest request,String clientId) {
		return ClientMonitor.loadRoomInfo(clientId);
	}
	
	@RequestMapping(value="/room.do",params = "monitorRoom")
	public ModelAndView monitingRoom(HttpServletRequest request) {
		return new ModelAndView("hotel/room/monitorRoom_ftl");
	}
	
	@RequestMapping(value="/room.do",params = "saveRoomInfos")
	@ResponseBody
	public ResultMessage saveRoomInfos(String data) {
		ResultMessage r = new ResultMessage();
		Map<String, Class> classMap = new HashMap<String, Class>();
		classMap.put("id", Long.class);
		classMap.put("serviceArea", String.class);
		classMap.put("type", String.class);
		classMap.put("roomNo", String.class);
		classMap.put("status", String.class);
		classMap.put("name", String.class);
		classMap.put("floor", String.class);
		classMap.put("deviceName", String.class);
		classMap.put("scene", String.class);
		classMap.put("deviceLinks", DeviceLinkItem.class);
		RoomItem roomItem = (RoomItem) JsonUtil.getObjByJson(data, RoomItem.class,classMap);
		//校验房间编号是否重复
//		if(roomService.checkIsExsit(roomItem.getId(),roomItem.getRoomNo())) {
			roomService.saveRoomInfos(roomItem);
			RoomMonitor.updateMonitorRoomInfo(roomItem);
//		}else {
//			r.setSuccess(false).setMsg("房间编号"+roomItem.getRoomNo()+"已存在");
//		}
		return r;
	}
	/**
	 * 验证配置是否重复
	 * 
	 * @author max.zheng
	 * @create 2015-4-5下午10:12:54
	 * @modified by
	 * @param id
	 * @param roomType
	 * @return  true 验证通过，false 验证不通过
	 */
	@RequestMapping(value="/room.do",params = "checkRoomNoIsExit")
	@ResponseBody
	public boolean checkRoomNoIsExit(String id,String roomNo) {
		if(StringUtils.isBlank(id)) id = "0";
		return !roomService.checkIsExsit(Long.valueOf(id),roomNo);
	}
	@RequestMapping(value="/room.do",params = "checkRcuIsExit")
	@ResponseBody
	public boolean checkRcuIsExit(String id,String roomDeviceName) {
		if(StringUtils.isBlank(id)) id = "0";
		return !roomService.checkRcuIsExit(Long.valueOf(id),roomDeviceName);
	}
	@RequestMapping(value="/room.do",params="loadRoomUnSelectDeviceLinks")
	@ResponseBody
	public Map<String, Object> loadRoomUnSelectDeviceLinks(String roomId) {
		Map<String, Object> results = roomService.loadRoomUnSelectDeviceLinks(roomId);
		return results;
	}
	@RequestMapping(value="/room.do",params="loadRoomSelectDeviceLinks")
	@ResponseBody
	public Map<String, Object> loadRoomSelectDeviceLinks(String roomId) {
		Map<String, Object> results = roomService.loadRoomSelectDeviceLinks(roomId);
		return results;
	}
	
	
	@RequestMapping(value="/room.do",params = "operationRoom")
	public ModelAndView operationRoom(HttpServletRequest request,Long roomId) {
		if (roomId!=null) {
			RoomItem roomItem = roomService.loadRoomItem(roomId);
			List<DeviceLinkItem> deviceLinkItems = roomItem.getDeviceLinks();
			for (DeviceLinkItem deviceLinkItem : deviceLinkItems) {
				ComponentHandler.loadComponent(deviceLinkItem);
			}
			request.setAttribute("deviceLinkItems", deviceLinkItems);
			List<CodeValueItem> nodeTypes = InitCacheData.dictionary.get("NODE_TYPE");
			Map<String, String> nodeTypeMap = new HashMap<String, String>();
			for (CodeValueItem codeValueItem : nodeTypes) {
				nodeTypeMap.put(codeValueItem.getValue(), codeValueItem.getName());
			}
			request.setAttribute("nodeTypeMap", nodeTypeMap);
			request.setAttribute("roomItem", roomService.loadRoomItem(roomId));
		}
		return new ModelAndView("hotel/room/operationRoom_ftl");
	}
	
	@RequestMapping(value="/room.do",params="downLoadRoomTemplate")
	public void downLoadRoomTemplate(HttpServletRequest request,HttpServletResponse response) {
		try
		{
			RoomItem item = new RoomItem();
			
			item.setDeviceIp("192.168.1.1");
			item.setDeviceSn("3518787878");
			item.setDeviceName("RCU-202");
			item.setDevicePort("9000");
			item.setRoomNo("202");
			item.setFloor("3楼");
			item.setName("202室");
			item.setServiceArea("COMMON-AREA");
			item.setStatus("4");
			item.setType("标准单人房");
	        List<RoomItem> items = new ArrayList<RoomItem>();
	        items.add(item);
	        String fileName = "room_template.xls";
	        String exportUrl = ApplicationContextUtil.getWebappUrl()+"template/";
	        File exportFile = new File(ApplicationContextUtil.getWebappUrl()+"template");
	        if (!exportFile.exists())
			{
				exportFile.mkdir();
			}
	        String fileUrl = exportUrl+"/"+fileName;
	        OutputStream out = new FileOutputStream(fileUrl);
			ExcelHelper.exportExcel("客房模版信息", item.getClass(), items, out);
			out.flush();
			out.close();
			
			//读写设定好的excel模版
	        InputStream fis = new BufferedInputStream(new FileInputStream(new File(fileUrl)));
	        byte[] buffer = new byte[fis.available()];
	        fis.read(buffer);
	        fis.close();
	        
	        response.setCharacterEncoding("UTF-8");
	        response.setHeader("Content-Disposition", "attachment;filename="+fileName);
	        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
	        response.setContentType("application/octet-stream");
	        toClient.write(buffer);
	        toClient.flush();
	        toClient.close();
		}
		catch (Exception e)
		{
			log.error("导出客房模版异常", e);
		}
	}

	@RequestMapping(value="/room.do",params = "skipToTempImport")
	public ModelAndView skipToTempImport() {
		return new ModelAndView("hotel/room/roomImportWin_ftl");
	}
	
	@RequestMapping(value="/room.do",params = "importRoomTempate")
	@ResponseBody
	public ResultMessage importRoomTempate(@RequestParam MultipartFile roomTemplateFile,HttpServletRequest request) {
		ResultMessage r = new ResultMessage();
		System.out.println(roomTemplateFile.getSize());
		try {
			List<RoomItem> items = ExcelHelper.importExcel(roomTemplateFile.getInputStream(), RoomItem.class);
			String rs = roomService.saveImportRoomInfos(items);
			if (StringUtils.isNotBlank(rs)) {
				r.setSuccess(false);
				r.setMsg(rs);
			}
		} catch (Exception e) {
			log.error("导入客房模版处理异常", e);
			r.setSuccess(false);
		}
		return r;
	}
	
	/**
	 * 加载非卡关联房间
	 * @param userId
	 * @return
	 */
	@RequestMapping(params = "loadCardUnSelectRooms")
	@ResponseBody
	public List<RoomItem> loadCardUnSelectRooms(Long cardId) {
		List<RoomItem> rooms = roomService.loadNotCardRooms(cardId);
		return rooms;
	}
	
	@RequestMapping(params = "loadCardSelectRooms")
	@ResponseBody
	public List<RoomItem> loadCardSelectRooms(Long cardId) {
		List<RoomItem> rooms = roomService.loadUserRoles(cardId);
		return rooms;
	}
}
